package profile

import (
	"context"
	rentalpb "coolcar/v1/rental/api/gen/v1"
	"coolcar/v1/shared/auth"
	"coolcar/v1/shared/ids"
	"encoding/base64"
	"fmt"
	"google.golang.org/protobuf/proto"
)

type Fetcher interface {
	GetProfile(ctx context.Context, request *rentalpb.GetProfileRequest) (*rentalpb.Profile, error)
}

// Manager defines a profile manager.
type Manager struct {
	Fetcher
}

// Verify verifies account identity.
func (m *Manager) Verify(ctx context.Context, id ids.AccountID) (ids.IdentityID, error) {
	auth.ContextWithAccountID(ctx, id)
	nilID := ids.IdentityID("")
	pr, err := m.Fetcher.GetProfile(ctx, &rentalpb.GetProfileRequest{})
	if err != nil {
		return nilID, fmt.Errorf("failed to get profile: %v", err)
	}
	if pr.IdentityStatus != rentalpb.IdentityStatus_VERIFIED {
		return nilID, fmt.Errorf("invalid identity id: %v", err)
	}
	bytes, err := proto.Marshal(pr.Identity)
	if err != nil {
		return nilID, fmt.Errorf("failed to marshal identity: %v", err)
	}
	return ids.IdentityID(base64.StdEncoding.EncodeToString(bytes)), nil
}
